<template>
  <div class="l-content">
    <div class="l-body">
      <div class="l-left">
        <div class="l-touxiang">
          <div v-if="currentUser.name == ''" @click="dialogTableVisible = true" style="cursor: pointer;"><el-avatar
              :icon="UserFilled" /></div>
          <div v-else><el-avatar src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" /></div>

        </div>
        <div v-if="currentUser.name == ''" class="l-name">未登录</div>
        <div v-else class="l-name">{{ currentUser.name }}</div>
        <div class="l-setting"><el-icon :size="25" color="#e8dbdb">
            <Tools />
          </el-icon></div>
      </div>
      <div class="l-center">
        <el-card class="l-card">
          <div> <el-input v-model="keywords" size="small" style="width: 140px" placeholder="搜索"
              @keyup.enter.native="onGetUserList" :suffix-icon="Search" />
          </div>

          <div class="l-user" v-for="item in contactUsers" @click="OnLineMsgWindows(item.id, item.name)">
            <el-avatar class="l-user-head" :size="35"
              src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" />
            <div class="l-user-body">
              <div class="l-user-body-name">{{ item.name }}</div>
              <div class="l-user-body-msg">
                <el-text class="l-w100" truncated>
                  {{ item.msg }}
                </el-text>

              </div>
            </div>
          </div>




        </el-card>
      </div>
      <div class="l-rigth">
        <div class="l-right-name">
          {{ currentOnLineUserName }}
        </div>
        <el-divider />
        <div class="l-right-msg" ref="scrollContainer">
          <!-- 聊天记录 -->
          <template v-for="item in contactOnLineLog">

            <div v-if="item.state == 1" class="l-msg-slef">
              <div>
                <div style="font-size: 8px;text-align: right;">{{ item.time }}</div>
                <div  class="l-user-text">{{ item.msg }}</div>
              </div>
              <el-avatar class="l-user-head" :size="35" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" />

            </div>
            <div v-else class="l-msg-pengyou">
              <el-avatar class="l-user-head" :size="35"
                src="https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg" />
              <!-- <div class="l-user-text">{{ item.msg }}</div> -->
              <div>
                <div style="font-size: 8px;text-align: left;">{{ item.time }}</div>
                <div  class="l-user-text">{{ item.msg }}</div>
              </div>
            </div>
          </template>


        </div>

        <div class="l-right-send">
          <div style="position: relative;" v-show="currentOnLineUserId != ''">
            <!-- @keyup.enter.native="onSendMsg" -->
            <el-input v-model="msg" @keyup.enter="handleEnter" style="width: 100%;" :rows="7" placeholder=""
              type="textarea" resize="none" />
            <el-icon style="position: absolute;bottom: 10px;right: 10px;cursor: pointer;" @click="onSendMsg">
              <Position />
            </el-icon>
          </div>
        </div>
      </div>
    </div>


    <el-dialog v-model="dialogTableVisible" :close-on-click-modal="false" title="登录/注册" width="500">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="账号">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" />
        </el-form-item>
        <el-form-item>
          <div style="text-align: right;width: 100%;">
            <el-button type="primary" @click="onLogin">登录</el-button>
            <el-button type="info" @click="onRegister">注册</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from "vue";
import { Search } from '@element-plus/icons-vue'
import { UserFilled } from '@element-plus/icons-vue'
import { Login, Register, GetUserList, GetOnLineMsgList, SendMsg } from "@/service/api";
import { ElMessage } from "element-plus";
import type { GetOnLineMsgListResponse, GetUserListResponse } from "@/service/apimodel";
import * as signalR from "@microsoft/signalr";
import { ApiBase } from "@/service/request";
const keywords = ref('');
const msg = ref('');
const input = ref('');
const dialogTableVisible = ref(false)
const currentOnLineUserName = ref('')
const currentOnLineUserId = ref('')
const scrollContainer = ref<any>(null)
const currentOnLineTime = ref<string>('')
const form = reactive({
  name: '',
  password: ''
})
const currentUser = reactive({
  id: '',
  name: '',
  accountNo: ''
})
// 好友列表
const contactUsers = ref<GetUserListResponse[]>([]);
//聊天记录
const contactOnLineLog = ref<GetOnLineMsgListResponse[]>([]);
/** 登录 */
function onLogin() {
  Login(form.name, form.password).then((res: any) => {

    if (res.success) {
      ElMessage({ message: '登录成功', type: 'success' })
      dialogTableVisible.value = false;
      localStorage.setItem("token", res.data.token);
      localStorage.setItem("userName", res.data.name);
      localStorage.setItem("accountNo", res.data.accountNo);
      localStorage.setItem("userPower", res.data.power);

      currentUser.id = res.data.id;
      currentUser.name = res.data.name;
      currentUser.accountNo = res.data.accountNo;
      onGetUserList();
      onSignalR();
    } else {
      ElMessage.error(res.msg)
    }
  })
    .catch((err) => { });
}

/** 注册 */
function onRegister() {
  Register(form.name, form.password).then((res: any) => {

    if (res.success) {
      ElMessage({ message: '注册成功', type: 'success' })

    } else {
      ElMessage.error(res.msg)
    }
  })
    .catch((err) => { });
}

/** 获取用户列表 */
function onGetUserList() {
  GetUserList(keywords.value).then((res: any) => {
    if (res.success) {
      console.log(res.data)
      contactUsers.value = res.data;

    } else {
      ElMessage.error(res.msg)
    }
  }).catch((err) => { });
}
/** 聊天 */
function OnLineMsgWindows(id: string, name: string) {
  currentOnLineUserId.value = id;
  currentOnLineUserName.value = name;
  OnLineMsgLog(false);
}
/** 聊天记录 */
function OnLineMsgLog(isPush: boolean) {
  if (isPush == false) { contactOnLineLog.value = []; }

  GetOnLineMsgList(currentOnLineUserId.value).then((res: any) => {
    if (res.success) {
      if (isPush) {
        //追加
        contactOnLineLog.value = res.data;
        for (let i = 0; i < res.data.length; i++) {
          const element = res.data[i];
          if (contactOnLineLog.value.some(item => item.id == element.id) == false) {
            contactOnLineLog.value.push(element);
          }
        }
      }
      else {
        //直接赋值
        contactOnLineLog.value = res.data;
      }

      if (contactOnLineLog.value != undefined && contactOnLineLog.value.length > 0) {
        currentOnLineTime.value = contactOnLineLog.value[contactOnLineLog.value.length - 1].time;
      }
      scrollMsg();
    } else {
      ElMessage.error(res.msg)
    }
  }).catch((err) => { });
}

/** 发送消息 */
function onSendMsg() {
  SendMsg(currentOnLineUserId.value, msg.value).then((res: any) => {

    if (res.success) {
      // ElMessage({ message: res.msg, type: 'success' })
      msg.value = "";
      OnLineMsgLog(true);
    } else {
      ElMessage.error(res.msg)
    }
  })
    .catch((err) => { });
}
/** 处理消息滚动条 */
const scrollMsg = () => {
  nextTick(() => {
    const content = scrollContainer.value
    content.scrollTo({ top: content.scrollHeight, behavior: "smooth" });
  })
}
/** input监听事件 */
const handleEnter = (event: any) => {
  if (!event.shiftKey) {
    // 这里处理 Enter 事件，未按下 Shift 键时的逻辑
    onSendMsg();
  }
};
onMounted(() => {

});
function onSignalR() {
  /**SignalR Hub */
  //连接到 SignalR Hub
  const url = ApiBase + "/chatHub"
  const connection = new signalR.HubConnectionBuilder()
    .withUrl(url)
    .build();
  connection.start().then(() => {
    console.log("连接成功");
  }).catch(err => console.error(err.toString()));
  //接收服务器端推送的消息
  connection.on("ReceiveMsg", (key, value) => {
    console.log("接收", key, value);
    onFrashData(key);
  });
  /**SignalR Hub */
}
function onFrashData(id: string) {
  onGetUserList();
  if (currentOnLineUserId.value == id) {
    OnLineMsgLog(true);
  }

}

</script>


<style scoped>
::-webkit-scrollbar {
  display: none;
}

.l-w100 {
  width: 100px;
  font-size: 9px;
  /* height: 20px; */
  line-height: 10px;
  color: gray;
  letter-spacing: 1px;
}

.l-content {
  width: 100%;
  height: 100vh;
  background-color: aliceblue;
  padding: 0px;
  margin: 0px;
  background: linear-gradient(to bottom, #b5e1f6, #faeceb);
  display: flex;
  justify-content: center;
  align-items: center;
}

.l-body {
  width: 900px;
  height: 560px;
  display: flex;

  .l-left {
    width: 60px;
    background-color: #8794ca;
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;

    .l-touxiang {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 60px;
    }

    .l-name {
      font-size: 10px;
      text-align: center;
      color: white;
      letter-spacing: 2px;
      height: 467px;
    }

    .l-setting {
      text-align: center;
      cursor: pointer;
    }
  }

  .l-center {
    width: 200px;
    background-color: aliceblue;
    padding: 5px;

    .l-card {
      width: 180px;
      height: 547px;

      .l-user {
        display: flex;
        align-items: center;
        height: 55px;
        /* border: 1px solid red; */
        line-height: 55px;
        cursor: pointer;

        .l-user-head {
          margin-right: 5px;
        }

        .l-user-body {
          width: 100px;

          .l-user-body-name {
            font-size: 12px;
            line-height: 20px;
            height: 20px;
            font-weight: bold;
            letter-spacing: 1px;
          }

          .l-user-body-msg {
            font-size: 9px;
            height: 20px;
            line-height: 10px;
            color: gray;
            letter-spacing: 1px;
          }
        }
      }
    }
  }

  .l-rigth {
    flex: 1;
    background-color: aliceblue;
    border-top-right-radius: 8px;
    border-bottom-right-radius: 8px;

    .l-right-name {
      letter-spacing: 4px;
      padding-top: 10px;
      font-weight: bold;
      color: gray;
      font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    }

    .l-right-msg {
      height: 300px;
      padding-right: 20px;
      font-size: 12px;
      overflow-y: scroll;

      /* border: 1px solid red; */
      .l-msg-slef {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 10px;

        .l-user-head {
          margin-left: 10px;
        }

        .l-user-text {
          /* flex: 1; */
          background-color: #8794ca;
          padding: 5px 10px;
          border-radius: 4px;
          color: white;
          max-width: 400px;
        }
      }

      .l-msg-pengyou {
        display: flex;
        margin-bottom: 10px;
        font-size: 12px;

        .l-user-head {
          /* width: 50px; */
          margin-right: 10px;
        }

        .l-user-text {
          /* flex: 1; */
          background-color: #d0d5d6;
          padding: 5px 10px;
          border-radius: 4px;
          color: rgb(63, 53, 53);
          max-width: 400px;
        }
      }
    }

    .l-right-send {
      padding-right: 10px;
      border-top: 1px solid #dcdfe6;
      height: 170px;
      padding-top: 10px;
    }
  }
}
</style>